package co.example.michael.bigpictureloading;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.File;

import co.example.michael.application.CustomApplication;
import co.example.michael.tools.PictureAllTools;


public class MainActivity extends Activity {

    private Button pictureButton;

    private Button netWorkButton;

    private final static int SELECT_REQUEST_CODE = 10;

    private ImageView imageView;

    private String pictureUrl = "http://img.my.csdn.net/uploads/201407/26/1406383248_3693.jpg";

    private final int ADD_PICTURE = 11;

    private Button uploadPictureButton;

    private String uploadPicturePath;

    private Button downloadPictureButton;

    private AsyncHttpClient asyncHttpClient;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ADD_PICTURE:
                    Bitmap bitmap = PictureAllTools.getBitmapFromMemoryCache(pictureUrl);
                    if (bitmap != null) {
                        imageView.setImageBitmap(bitmap);
                        Log.e("MainActivity:", "从内存中取出图片并初始化");
                    } else {
                        bitmap = PictureAllTools.getBitmapFromDisk(pictureUrl);
                        if (bitmap != null) {
                            imageView.setImageBitmap(bitmap);
                            Log.e("MainActivity:", "从sd卡中取出图片并初始化");
                        }
                    }
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        asyncHttpClient = new AsyncHttpClient();
        imageView = (ImageView) findViewById(R.id.one_image_view);
        initImageView();
        uploadPictureButton = (Button) findViewById(R.id.upload_picture_button);
        pictureButton = (Button) findViewById(R.id.one_button);
        pictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DialogActivity.class);
                startActivityForResult(intent, SELECT_REQUEST_CODE);
            }
        });

        netWorkButton = (Button) findViewById(R.id.network_button);
        netWorkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NetworkActivity.class);
                startActivity(intent);
            }
        });

        uploadPictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "点击了", Toast.LENGTH_SHORT).show();
                uploadPictureButtonListener();
            }
        });

        downloadPictureButton = (Button)findViewById(R.id.download_picture_button);
        downloadPictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadPictureButtonListener();
            }
        });

    }

    /**
     * 初始化界面
     */
    private void initImageView() {
        Bitmap bitmap = PictureAllTools.getBitmapFromMemoryCache(pictureUrl);
        if (bitmap == null) {
            bitmap = PictureAllTools.getBitmapFromDisk(pictureUrl);
            if (bitmap == null) {
                new Thread() {
                    @Override
                    public void run() {
                        PictureAllTools.addBitmapToDiskAndMemory(pictureUrl);
                        Message message = new Message();
                        message.what = ADD_PICTURE;
                        handler.sendMessage(message);
                        Log.e("MainActivity:", "要下载图片");
                    }
                }.start();
            } else {
                imageView.setImageBitmap(bitmap);
                Log.e("MainActivity:", "没有下载，从sd卡中取出图片");

            }
        } else {
            imageView.setImageBitmap(bitmap);
            Log.e("MainActivity:", "没有下载，从内存中取出图片");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case FinalConstant.ALBUM_RESULT_CODE:
                uploadPicturePath = "";
                Uri uri = data.getData();
                String path = PictureAllTools.getPathFromUri(MainActivity.this, uri);
                Log.e("图片的物理路径：", path);
                uploadPicturePath = path;

                PictureAllTools.setImageView(imageView, path);

                break;
            case FinalConstant.CAMERA_RESULT_CODE:

                String cameraPath = Environment.getExternalStorageDirectory() + "/Android/data/MichealCamera/temp.jpg";

                Log.e("拍照的图片的路径：", cameraPath);

                PictureAllTools.setImageView(imageView, cameraPath);
                break;
        }
    }

    @Override
    protected void onPause() {
        try {
            CustomApplication.diskLruCache.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try {
            CustomApplication.diskLruCache.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    /**
     * 上传图片的测试
     */
    private void uploadPictureButtonListener() {
        File file = null;
        file = new File(uploadPicturePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        String url = "https://upload.api.weibo.com/2/statuses/upload.json";

        RequestParams params = new RequestParams();

        params.put("access_token", "2.00UZLiWD0sfgia4e16d208e80gcGFt");
        params.put("status", "上传图片啊");
        try {
            //pic是参数中的key,这是在微博接口中的
            params.put("pic", file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        asyncHttpClient.post(MainActivity.this, url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.e("返回码：", "" + i);
                String backData = new String(bytes);
                Log.e("返回的数据：", backData);
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }

    /**
     * 下载图片测试
     */
    private void downloadPictureButtonListener(){
        String url ="http://img.my.csdn.net/uploads/201407/26/1406383166_7301.jpg";

        asyncHttpClient.get(MainActivity.this,url,new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                imageView.setImageBitmap(bitmap);
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                 throwable.printStackTrace();
            }
        });
    }
}
